import { PermissionState } from './types';
import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { constantRoutes,asyncRoutes } from '@/router';
import { listRoutes } from '@/api/menu';

const modules = import.meta.glob('../../views/**/**.vue');
export const Layout = () => import('@/layout/index.vue');

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
  if (route.meta && route.meta.roles) {
    if (roles.includes('ROOT')) {
      return true;
    }
    return roles.some(role => {
      if (route.meta?.roles !== undefined) {
        return (route.meta.roles as string[]).includes(role);
      }
    });
  }
  return false;
};

export const filterAsyncRoutes = (
  routes: RouteRecordRaw[]
) => {
  const res: RouteRecordRaw[] = [];
  routes.forEach(route => {
    const tmp = { ...route } as any;
    // console.log(tmp)
    if (tmp.path == '/') {
      tmp.component = Layout;
    } else {
      const component = modules[`../../views/${tmp.name}/index.vue`] as any;
      // const component = modules[`../../views/${tmp.component}.vue`] as any;
      if (component) {
        tmp.component = component;
      } else {
        tmp.component = modules[`../../views/error-page/404.vue`];
      }
    }
    res.push(tmp);

    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children);
    }
    // if (hasPermission(roles, tmp)) {
    //   if (tmp.component == 'Layout') {
    //     tmp.component = Layout;
    //   } else {
    //     const component = modules[`../../views/${tmp.name}.vue`] as any;
    //     // const component = modules[`../../views/${tmp.component}.vue`] as any;
    //     if (component) {
    //       tmp.component = component;
    //     } else {
    //       tmp.component = modules[`../../views/error-page/404.vue`];
    //     }
    //   }
    //   res.push(tmp);

    //   if (tmp.children) {
    //     tmp.children = filterAsyncRoutes(tmp.children, roles);
    //   }
    // }
  });
  return res;
};

const usePermissionStore = defineStore({
  id: 'permission',
  state: (): PermissionState => ({
    routes: constantRoutes || [],
    addRoutes: []
  }),
  actions: {
    setRoutes(routes: RouteRecordRaw[]) {
      this.addRoutes = routes;
      this.routes = constantRoutes.concat(routes);
    },
    generateRoutes() {
      return new Promise((resolve, reject) => {
        const accessedRoutes = filterAsyncRoutes(asyncRoutes);
        this.setRoutes(accessedRoutes);
        resolve(accessedRoutes);
        // listRoutes()
        //   .then(response => {
        //     const resRoutes = response.data;
        //     const accessedRoutes = filterAsyncRoutes(resRoutes, roles);
        //     this.setRoutes(accessedRoutes);
        //     resolve(accessedRoutes);
        //   })
        //   .catch(error => {
        //     reject(error);
        //   });
      });
    }
  }
});

export default usePermissionStore;
